<template>
    <el-form :inline="true" :model="searchData" style="text-align: center;" class="demo-form-inline">
        <el-form-item label="生产批次">
            <el-input v-model="searchData.batch" placeholder="生产批次" style="width: 120px;" clearable />
        </el-form-item>
        <el-form-item label="商品名称">
            <el-select v-model="searchData.goodNo" placeholder="请选择商品" style="width: 120px;" clearable>
                <el-option v-for="item in goodsList" :key="item.goodNo" :label="item.goodName" :value="item.goodNo" />
            </el-select>
        </el-form-item>
        <el-form-item label="保质期">
            <el-input v-model="searchData.deadline" placeholder="保质期" style="width: 120px;" clearable />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" style="width: 80px;" @click="getSourceist()">查询</el-button>
            <el-button type="success" style="margin: 0px 5px;width: 80px;"
                @click="dialogVisible = true, resetForm(ruleFormRef)">新增</el-button>
            <el-button type="danger" style="margin: 0px 5px;width: 80px;" @click="batchDeleteSource">删除</el-button>
        </el-form-item>
    </el-form>
    <el-table :data="sourceList" style="width: 120%" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center">
        </el-table-column>
        <el-table-column type="index" label="序号" width="60" align="center" :index="indexMethod" />
        <el-table-column prop="goodName" label="商品名称" width="150" align="center" />
        <el-table-column prop="productionBatch" label="生产批次" width="110" align="center" />
        <el-table-column prop="shelfLife" label="保质期(天)" width="100" align="center" />
        <el-table-column prop="productionLicenseNumber" label="生产许可证" width="180" align="center" />
        <el-table-column prop="productionEnterprise" label="生产企业" width="210" align="center" />
        <el-table-column prop="" label="信息完善度" width="100" align="center" />
        <el-table-column prop="createBy" label="创建人" width="100" align="center" />
        <el-table-column prop="createDate" label="创建时间" width="180" align="center">
            <template v-slot="scope">
                {{ scope.row.createDate.split("T")[0] }}
            </template>
        </el-table-column>
        <el-table-column prop="updateBy" label="修改人" width="100" align="center" />
        <el-table-column prop="updateDate" label="修改时间" width="180" align="center">
            <template v-slot="scope">
                {{ scope.row.updateDate ? scope.row.updateDate.split("T")[0] : "" }}
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="225">
            <template v-slot="scope">
                <el-link type="primary" size="small"
                    @click="pushEdit(scope.row.sourceId, scope.row.productionBatch)">详情</el-link>
                &ensp;
                <el-link type="primary" size="small" @click="updateSource(scope.row.sourceId)">修改</el-link>
                &ensp;
                <el-link type="primary" size="small">导出溯源码</el-link>
                &ensp;
                <el-link type="danger" size="small" @click="deleteSource(scope.row.sourceId)">删除</el-link>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页 -->
    <table style="margin: 5px auto;">
        <tbody>
            <tr>
                <td>
                    <el-pagination v-model:current-page="page.index" v-model:page-size="page.size"
                        :page-sizes="[15, 20, 25, 30]" background layout="slot" :total="page.totalCount"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页"
                        next-text="下一页">
                        <span>
                            共 {{ page.totalCount }} 条，共 {{ page.pageCount }} 页，当前 {{ page.index }} / {{ page.pageCount
                            }} 页
                        </span>
                    </el-pagination>
                </td>
                <td>
                    <el-pagination v-model:current-page="page.index" v-model:page-size="page.size"
                        :page-sizes="[15, 20, 25, 30]" background layout="sizes, slot,prev, pager, next"
                        :total="page.totalCount" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        prev-text="上一页" next-text="下一页">
                        <span>
                            <button @click="handleCurrentChange(1)" :disabled="page.index == 1">首页</button>
                        </span>
                    </el-pagination>
                </td>
                <td>
                    <el-pagination v-model:current-page="page.index" v-model:page-size="page.size"
                        :page-sizes="[15, 20, 25, 30]" background layout="slot,jumper" :total="page.totalCount"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页"
                        next-text="下一页">
                        <span>
                            <button @click="handleCurrentChange(page.pageCount)"
                                :disabled="page.index == page.pageCount">尾页</button>
                        </span>
                    </el-pagination>
                </td>
            </tr>
        </tbody>
    </table>
    <el-dialog v-model="dialogVisible" title="基本信息" width="500">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="sourceInfo" :rules="rules" label-width="auto"
            class="demo-ruleForm" :size="formSize" status-icon>
            <el-form-item label="商品名称" prop="goodNo">
                <el-select v-model="sourceInfo.goodNo" placeholder="请选择商品" clearable>
                    <el-option v-for="item in goodsList" :key="item.goodNo" :label="item.goodName"
                        :value="item.goodNo" />
                </el-select>
            </el-form-item>
            <el-form-item label="生产批次" prop="productionBatch">
                <el-input v-model="sourceInfo.productionBatch" />
            </el-form-item>
            <el-form-item label="保质期（天）" prop="shelfLife">
                <el-input v-model="sourceInfo.shelfLife" />
            </el-form-item>
            <el-form-item label="生产许可证号" prop="productionLicenseNumber">
                <el-input v-model="sourceInfo.productionLicenseNumber" />
            </el-form-item>
            <el-form-item label="生产企业" prop="productionEnterprise">
                <el-input v-model="sourceInfo.productionEnterprise" />
            </el-form-item>
            <el-form-item label="封面图" prop="goodPicture">
                <el-upload class="avatar-uploader" action="http://localhost:5124/api/File/UploadFile"
                    :on-success="handleAvatarSuccess" :on-remove="handleRemove" :limit="1">
                    <img v-if="sourceInfo.goodPicture" :src="`http://localhost:5124/Images/` + sourceInfo.goodPicture"
                        class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
            <el-button type="primary" @click="resetForm(ruleFormRef)">重置</el-button>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>

import { reactive, ref, onMounted, inject } from "vue";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import http from '@/http'
const router = useRouter()

const searchData = reactive({
    goodNo: '',     // 商品名称
    batch: '',      // 生产批次
    deadline: '',   // 保质期
})


//跳转详情
const pushEdit = (id: number, productionBatch: string) => {
    router.push('/SourceDetailView?sourceId=' + id)
    //批次号
    sessionStorage.setItem('productionLot', productionBatch)
}

const sourceList = ref([]);
const selSourceList = ref<{
    sourceId: ''
}[]>([]);

// 复选框选中事件
const handleSelectionChange = (val: any) => {
    selSourceList.value = val;
}
//分页变量
const page = reactive({
    index: 1,
    size: 15,
    totalCount: 0,
    pageCount: 0,
})

// 序号
const indexMethod = (index: number) => {
    return index += (page.size) * (page.index - 1) + 1;
}

//分页方法
const handleSizeChange = (val: number) => {
    page.size = val;
    getSourceist();
}
const handleCurrentChange = (val: number) => {
    page.index = val;
    getSourceist();
}

// 删除
const deleteSource = (sourceId: number) => {
    ElMessageBox.confirm(
        '确定删除该溯源商品',
        '确认删除',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error',
        }
    )
        .then(() => {
            http.delete("/api/Source/SourceDelete?SourceId=" + sourceId).then(res => {
                if (res.data > 0) {
                    ElMessage.success("删除成功");
                    getSourceist();
                } else {
                    ElMessage.error("删除失败，请稍后再试");
                }
            })
        })
        .catch(() => {
        })
}

// 批量删除
const batchDeleteSource = () => {
    let length = selSourceList.value.length;
    if (selSourceList.value.length == 0) {
        ElMessage({
            type: 'warning',
            message: '至少选择一项要删除的溯源信息！',
            duration: 2000
        });
        return;
    }
    ElMessageBox.confirm(
        '确定删除已选的' + length + '个溯源商品?',
        '确认删除',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error',
        }
    )
        .then(() => {
            let ids = selSourceList.value.map(x => x.sourceId).join(",");
            http.delete("/api/Source/SourceBacthLogicDelete?sourceIds=" + ids).then(res => {
                if (res.data > 0) {
                    ElMessage({
                        type: 'success',
                        message: "已删除" + length + "个溯源商品",
                        duration: 2000
                    });
                    // 刷新当前页面
                    getSourceist();
                } else {
                    ElMessage({
                        type: 'success',
                        message: "删除失败，请稍后再试",
                        duration: 2000
                    })
                }
            })
        })
        .catch(() => {
        })
}

// 获取溯源列表
const getSourceist = () => {
    http.get("/api/Source/GetSourceInfoList", {
        params: {
            goodNo: searchData.goodNo || 0,
            batch: searchData.batch,
            deadline: searchData.deadline || 0,
            size: page.size,
            index: page.index,
        }
    }).then(res => {
        sourceList.value = res.data.datas;
        page.totalCount = res.data.totalCount;
        page.pageCount = res.data.pageCount;
    })
}

// 修改溯源信息
const updateSource = (sourceId: number) => {
    dialogVisible.value = true;
    http.get("/api/Source/GetSourceInfoById?SourceId=" + sourceId).then(res => {
        sourceInfo.sourceId = res.data.sourceId;
        sourceInfo.sourceId = res.data.sourceId;
        sourceInfo.sourceNo = res.data.sourceNo;
        sourceInfo.goodNo = res.data.goodNo;
        sourceInfo.goodName = res.data.goodName;
        sourceInfo.shelfLife = res.data.shelfLife;
        sourceInfo.productionBatch = res.data.productionBatch;
        sourceInfo.productionLicenseNumber = res.data.productionLicenseNumber;
        sourceInfo.productionEnterprise = res.data.productionEnterprise;
        sourceInfo.goodPicture = res.data.goodPicture;
        sourceInfo.productInspectionReport = res.data.productInspectionReport;
        sourceInfo.createBy = res.data.createBy;
        sourceInfo.createDate = res.data.createDate;
        sourceInfo.updateBy = res.data.updateBy;
        sourceInfo.updateDate = res.data.updateDate;
        sourceInfo.isDelete = res.data.isDelete;
    })
}

// 弹框显示
const sourceInfo = reactive({
    sourceId: 0,
    sourceNo: "2314234214321",
    goodNo: "",
    goodName: "",
    shelfLife: "",
    productionBatch: "",
    productionLicenseNumber: "SC211201027680",
    productionEnterprise: "成都爱吃兔食品加工有限公司",
    goodPicture: "",
    productInspectionReport: "",
    createBy: "张三",
    createDate: "2024-04-02T03:52:02.937Z",
    updateBy: "",
    updateDate: "2024-04-02T03:52:02.937Z",
    isDelete: false
})


const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    goodNo: [
        { required: true, message: '请选择商品', trigger: 'change' },
    ],
    shelfLife: [
        { required: true, message: '请输入保质期', trigger: 'blur' },
        { pattern: /^[0-9]*$/, message: '保质期只能为数字', trigger: 'blur' },
    ],
    productionBatch: [
        { required: true, message: '请输入生产批次', trigger: 'blur' },
        { min: 1, max: 30, message: '最多输入30字符', trigger: 'blur' },
    ],
    productionLicenseNumber: [
        { required: true, message: '请输入生产许可证号', trigger: 'blur' },
        { min: 1, max: 30, message: '最多输入30字符', trigger: 'blur' },
        { pattern: /^[A-Za-z0-9]{4,40}$/, message: '生产许可证只能为数字,字母组合', trigger: 'blur' },
    ],
    productionEnterprise: [
        { required: true, message: '请输入生产企业', trigger: 'blur' },
        { min: 1, max: 30, message: '最多输入30字符', trigger: 'blur' },
        { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '生产企业只能为汉字或英文', trigger: 'blur' },
    ],
    goodPicture: [
        { required: true, message: '请上传封面图', trigger: 'change' },
    ],
})

const dialogVisible = ref(false)

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
            // 溯源Id为0，则为添加
            if (sourceInfo.sourceId == 0) {
                http.post("/api/Source/SourceInsert", sourceInfo).then(res => {
                    if (res.data > 0) {
                        ElMessage({
                            type: "success",
                            message: "保存成功",
                            duration: 2000
                        });
                        dialogVisible.value = false;
                        getSourceist();
                    }
                    else if (res.data == -1) {
                        ElMessage({
                            type: "error",
                            message: "该商品已存在溯源信息",
                            duration: 2000
                        });
                    }
                    else {
                        ElMessage({
                            type: "error",
                            message: "保存失败",
                            duration: 2000
                        })
                    }
                })
            }
            // 溯源Id不为0，则为修改
            else {
                http.put("/api/Source/SourceUpdate", sourceInfo).then(res => {
                    console.log(res.data);
                    if (res.data > 0) {
                        ElMessage({
                            type: "success",
                            message: "修改成功",
                            duration: 2000
                        });
                        dialogVisible.value = false;
                        getSourceist();
                    }
                    else if (res.data == -1) {
                        ElMessage({
                            type: "error",
                            message: "该商品已存在溯源信息",
                            duration: 2000
                        });
                    }
                    else {
                        ElMessage({
                            type: "error",
                            message: "修改失败",
                            duration: 2000
                        })
                    }
                })
            }
        } else {
        }
    })
}

// 重置表单信息
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

// 获取商品列表信息
const goodsList = ref<{
    goodNo: number,
    goodName: string
}[]>([])

const getGoodsList = () => {
    http.get("/api/Source/GetGoodsList").then(res => {
        goodsList.value = res.data;
    })
}

// 图片上传
const handleAvatarSuccess = (data: any) => {
    sourceInfo.goodPicture = data;
}

// 删除活动展示照片
const handleRemove = () => {
    sourceInfo.goodPicture = '';
}

onMounted(() => {
    // 获取商品列表
    getGoodsList();
    // 获取溯源列表
    getSourceist();
})

</script>
<style>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>